package main

import (
	"strconv"

	"gitee.com/bon-ami/eztools/v4"
)

const errorProof = false

// GetMembers returns members of team by ID
// return values: [][0] ID, [][1] Name
func GetMembers(db *eztools.Dbs, id int) ([][]string, error) {
	if id == eztools.InvalidID {
		return nil, eztools.ErrInvalidInput
	}
	team, err := db.Search(tblContacts,
		fldId+"="+strconv.Itoa(id), []string{fldsStrs[fldsIndTeam]}, "")
	if err != nil {
		return nil, err
	}
	if len(team) < 1 {
		return nil, eztools.ErrNoValidResults
	}
	leader, err := db.Search(tblTeam,
		fldId+"="+team[0][0],
		[]string{fldLeader}, "")
	if err != nil {
		return nil, err
	}
	if len(leader) < 1 || leader[0][0] != strconv.Itoa(id) {
		return nil, eztools.ErrInvalidInput
	}
	members, err := db.Search(tblContacts,
		fldsStrs[fldsIndTeam]+"="+team[0][0],
		[]string{fldId, fldsStrs[fldsIndName]}, "")
	return members, err
}

// MakeLeader makes user with id leader of team
//  if id not provided, current team members are listed,
//  and input is required to choose one
func MakeLeader(db *eztools.Dbs, id, team string) error {
	var (
		teamMembers, teamID [][]string
		err                 error
	)
	if len(id) < 1 {
		teamMembers, err = db.Search(tblContacts,
			fldsStrs[fldsIndTeam]+"="+team, []string{fldId, "name"}, "")
		if err != nil {
			return err
		}
		teamID, err = db.Search(tblTeam,
			fldId+"="+team, []string{fldLeader}, "")
		if err != nil {
			return err
		}
		lt := len(teamID)
		switch {
		case lt <= 0:
			eztools.ShowStrln("No team found!")
			return nil
		case lt > 1:
			eztools.ShowStrln("Multiple teams found with same ID!")
			return nil
		}
		eztools.ShowStr("Members of team: ")
		for _, member := range teamMembers {
			if teamID[0][0] == member[0] {
				eztools.ShowStr("[leader]")
			}
			eztools.ShowStr(member[0] + " " + member[1] + ", ")
		}
		id = eztools.PromptStr("ID of new leader=")
		if len(id) < 1 {
			return eztools.ErrInvalidInput
		}
	}
	if errorProof {
		teamMembers, err = db.Search(tblContacts,
			fldId+"="+id, nil, "")
		if err != nil || len(teamMembers) < 1 {
			eztools.ShowStrln("invalid ID")
			return eztools.ErrNoValidResults
		}
	}
	return db.UpdateWtParams(tblTeam, fldId+"="+team,
		[]string{fldLeader}, []string{id}, false, false)
}
